package hc.bre.rest.admin

import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.IncorrectCredentialsException
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.crypto.SecureRandomNumberGenerator
import org.apache.shiro.crypto.hash.Sha256Hash
import org.apache.shiro.subject.Subject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

import hc.bre.FunctionConfig

@groovy.transform.CompileStatic
@RestController
@RequestMapping("/admin")
class BreAdminController {
	protected static final Logger _log = LoggerFactory.getLogger(this.class);

	@Autowired
	BreAdminService authService;

	@RequestMapping("/login")
	public Object login(@RequestBody Map map) {
		BreUser usr = authService.login(map['usercode'] as String,
				map['userpwd'] as String,
				map['rememberMe']?true:false);
		return userinfo(usr);
	}

	@GetMapping("/user")
	public Object user() {
		return userinfo(AuthUtil.user());
	}

	@GetMapping("/logout")
	public void logout() {
		authService.logout()
	}

	@PostMapping("/changePwd")
	public Object changePwd(@RequestBody Map map) {
		String usercode = map['usercode'];
		String userpwd = map['userpwd'];
		String newpwd = map['newpwd'];
		BreUser usr = authService.changePwd(usercode,userpwd,newpwd);
		return userinfo(usr);
	}

	@GetMapping("/load")
	public BreAdminConfig load() {
		AuthUtil.permit(BrePermission.authAdmin) {
			authService.load();
		}
	}

	@PostMapping("/save")
	public Object save(@RequestBody Map map) {
		AuthUtil.permit(BrePermission.authAdmin) { 
			authService.save(map);
		}
	}

	@GetMapping("/projectTree")
	public Object projectTree() {
		authService.resourceList();
	}

	private Object userinfo(BreUser user) {
		return user?[id:user.id,code:user.code,name:user.name,perms:user.perms]:[:];
	}
}
